<?php
namespace App\Model;

use PhalApi\Model\NotORMModel as NotORM;

class Area extends NotORM {

    //设置表名
    protected function getTableName($id) {
        return 'region';
    }

    // 按获取区域
    public function getArea( $condition ) {
        return $this->getORM()
            ->select('id,name')
            ->where( $condition )
            ->fetchAll();
    }

    // 按条件获取地址
    public function getAddressList( $user_id ) {
        $orm = \PhalApi\DI()->notorm->user_address;
        return $orm
            ->select('address_id,consignee,province,city,district,address,mobile,is_default')
            ->where( array('user_id'=>$user_id) )
            ->order( 'is_default DESC' )
            ->fetchAll();
    }

    // 按条件获取区域名称
    public function getAreaInfo( $id ) {
        return $this->getORM()
            ->select('name')
            ->where( array('id'=>$id) )
            ->fetchOne();
    }

    // 添加地址
    public function insertAddress( $data ) {
        $orm = \PhalApi\DI()->notorm->user_address;
        $orm->insert( $data );
        return $orm->insert_id();
    }

    // 添加默认地址
    public function insertAddressDefult( $data ) {
        $orm = \PhalApi\DI()->notorm->user_address;
            $orm
            ->where( array('user_id'=>$data['user_id'],'is_default'=>1) )
            ->update( array( 'is_default' => 0 ) );
        $orm->insert( $data );
        return $orm->insert_id();
    }

    // 编辑地址
    public function editAddress( $user_id, $address_id, $data ) {
        $orm = \PhalApi\DI()->notorm->user_address;
        return $orm
            ->where( array('address_id'=>$address_id,'user_id'=>$user_id) )
            ->update( $data );
    }

    // 编辑默认地址
    public function editAddressDefult( $user_id, $address_id, $data ) {
        $orm = \PhalApi\DI()->notorm->user_address;
           return $orm
            ->where( array('user_id'=>$user_id,'is_default'=>1) )
            ->update( array( 'is_default' => 0 ) );
    }

    // 删除地址
    public function addressDel( $user_id, $address_id ) {
        $orm = \PhalApi\DI()->notorm->user_address;
        return $orm
            ->where( array('address_id'=>$address_id,'user_id'=>$user_id) )
            ->delete();
    }

    // 自动至为默认地址
    public function addressChange( $user_id ) {
        $orm = \PhalApi\DI()->notorm->user_address;
        $res =  $orm
            ->select('address_id')
            ->where( array('user_id'=>$user_id) )
            ->order( 'add_time DESC' )
            ->limit( 1 )
            ->fetchOne();
        return $orm
            ->where( array('address_id'=>$res['address_id'],'user_id'=>$user_id) )
            ->update( array('is_default'=>1) );
    }

    //查询某个地址
    public function addressMessage( $address_id ) {
        $orm = \PhalApi\DI()->notorm->user_address;
        return $orm
            ->select('is_default')
            ->where( array('address_id'=>$address_id) )
            ->fetchOne();
    }
}
